<?php
namespace Demo;

use PDO;
use PDOException;

class ArticleModel
{
    private PDO $pdo;
    
    public function __construct(array $config)
    {
        try {
            $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset=utf8mb4";
            $this->pdo = new PDO(
                $dsn,
                $config['username'],
                $config['password'],
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                ]
            );
        } catch (PDOException $e) {
            throw new RuntimeException("数据库连接失败：" . $e->getMessage());
        }
    }
    
    /**
     * 存储文章（所有字段均通过参数传入）
     * @param string $idstr 字符串ID（外部传入）
     * @param string $title 文章标题（外部传入）
     * @param string $content 文章内容（外部传入）
     * @param int $simhash 哈希值（计算后传入）
     * @param string $source 数据来源（外部传入）
     */
    public function saveArticle(
        string $idstr,
        string $title,
        string $content,
        int $simhash,
        string $source
    ): bool {
        // 严格校验必填参数
        if (empty($idstr) || empty($title) || empty($content) || empty($source)) {
            throw new InvalidArgumentException("idstr、title、content、source均为必填参数");
        }
        
        $stmt = $this->pdo->prepare("
            INSERT INTO articles (idstr, title, content, simhash, source, created_at)
            VALUES (:idstr, :title, :content, :simhash, :source, NOW())
        ");
        
        return $stmt->execute([
            ':idstr' => $idstr,
            ':title' => $title,
            ':content' => $content,
            ':simhash' => $simhash,
            ':source' => $source
        ]);
    }
    
    /**
     * 通过idstr查询所有匹配的文章
     */
    public function getArticlesByIdstr(string $idstr): array
    {
        $stmt = $this->pdo->prepare("
            SELECT * FROM articles WHERE idstr = :idstr
        ");
        $stmt->execute([':idstr' => $idstr]);
        return $stmt->fetchAll() ?: [];
    }
    
    /**
     * 按来源获取文章
     */
    public function getArticlesBySource(string $source): array
    {
        $stmt = $this->pdo->prepare("
            SELECT id, idstr, title, simhash, source FROM articles WHERE source = :source
        ");
        $stmt->execute([':source' => $source]);
        return $stmt->fetchAll() ?: [];
    }
    
    /**
     * 获取所有文章的关键信息
     */
    public function getAllSimhashes(): array
    {
        $stmt = $this->pdo->query("
            SELECT id, idstr, title, simhash, source FROM articles
        ");
        return $stmt->fetchAll() ?: [];
    }
}
